package com.ihighest.app.infox.activity;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.api.ApiCallback;
import com.ihighest.app.common.api.ApiParam;
import com.ihighest.app.common.api.ApiResult;
import com.ihighest.app.common.core.Application;
import com.ihighest.app.common.kit.DataCacheTools;
import com.ihighest.app.common.kit.SharedPreferencesKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.adapter.Nj_Pager_Adapter;
import com.ihighest.app.infox.fragment.Nj_Fragment_Myquestion;
import com.ihighest.app.infox.fragment.Nj_Fragment_Waitforyou;
import com.ihighest.app.infox.fragment.Nj_Fragment_near;
import com.ihighest.app.infox.fragment.Nj_Fragment_new;
import com.ihighest.app.infox.myview.ActivityTitle;
//import com.baidu.location.LocationClient;
//import com.baidu.location.LocationClientOption;
//import com.baidu.location.LocationClientOption.LocationMode;

/**
 * 农技界面
 * 
 * @author lkx Created at 2015-10-2 下午3:44:14
 * @version 1.0
 */
public class AgriculturalTechnologyActivity extends FragmentActivity implements OnClickListener {
	private static final String TAG = "AgriculturalTechnologyActivity";
	// public static LocationClient mLocationClient = null;
	public static ArrayList<String> imagelist;
	public static JSONObject questionobj;
	TextView result, mapLocation;
	// private Button open, close;
	private ActivityTitle title;
	private ViewPager nj_viewpager;
	// private ArrayList<View> nj_viewpager_list;
	private ArrayList<Fragment> nj_viewpager_list;
	TextView id_weather_city_tv;
	private Nj_Pager_Adapter nj_viewpager_adapter;
	// private NewListViewAdapter newlistviewadapter;
	private Nj_Fragment_new nj_fragment_new;
	private Nj_Fragment_near nj_fragment_near;
	private Nj_Fragment_Myquestion nj_fragment_myquestion;
	private Nj_Fragment_Waitforyou nj_fragment_waitforyou;
	private RadioButton radioButton_new;
	private RadioButton radioButton_near;
	private RadioButton radioButton_myquestion;
	private RadioButton radioButton_waitforyou;
	private long exitTime = 0;
	private ImageView request_ImageView;
	private ImageView getLocationImageView;
	LinearLayout weather_linearlayout;
	private int screenWidth;
	private int screenHeight;
	private int lastX, lastY;
	private TextView mWeather;// 天气
	private TextView mTemp;// 温度
	private ChangeBroadcast changeBroadcast;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Application.getInstance().addActivity(this);
		setContentView(R.layout.infox_activity_agricultural_technology);
		imagelist = new ArrayList<String>();
		ititView();
		loadData();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.e("", "进入nj");

		if (Const.UNREADMESSAGE != 0) {
			title.messagenumber.setText(Const.UNREADMESSAGE + "");
			title.messagenumber.setVisibility(View.VISIBLE);
		}else{
			title.messagenumber.setVisibility(View.GONE);
		}
	}

	private void loadData() {
		try {
			findViewById(R.id.weather).setVisibility(View.GONE);
			if (SharedPreferencesKit.getJsonObject(this, Const.SP_KEY_BD_LOCAITON) != null
					&& !TextUtils.isEmpty(SharedPreferencesKit.getJsonObject(this, Const.SP_KEY_BD_LOCAITON).getString("cityCode"))
					&& !SharedPreferencesKit.getJsonObject(this, Const.SP_KEY_BD_LOCAITON).getString("cityCode").equalsIgnoreCase("null")) {
				Api.get("weather", ApiParam.create().addParam("type", "fof"), new ApiCallback(this, true) {

					@Override
					public void handleSuccess(ApiResult result) {
						try {
							JSONObject json = new JSONObject(result.getData().getString("resp"));
							DataCacheTools.putJsonObject(mContext, Const.WEATHERINFO, json.getJSONObject("c"));
							DataCacheTools.putJsonArray(mContext, Const.WEATHERINFO, json.getJSONObject("f").getJSONArray("f1"));
							String wth = "";
							String dayWeather = DataCacheTools.getJsonArray(mContext, Const.WEATHERINFO).getJSONObject(0).getString("fa");
							String nightWeather = DataCacheTools.getJsonArray(mContext, Const.WEATHERINFO).getJSONObject(0).getString("fb");
							switch (dayWeather) {

							case "00":
								wth = "晴";
								break;
							case "01":
								wth = "多云";
								break;
							case "02":
								wth = "阴";
								break;
							case "03":
								wth = "阵雨";
								break;
							case "04":
								wth = "雷阵雨";
								break;
							case "05":
								wth = "雷阵雨伴有冰雹";
								break;
							case "06":
								wth = "雨夹雪";
								break;
							case "07":
								wth = "小雨";
								break;
							case "08":
								wth = "中雨";
								break;
							case "09":
								wth = "大雨";
								break;
							case "10":
								wth = "暴雨";
								break;
							case "11":
								wth = "大暴雨";
								break;
							case "12":
								wth = "特大暴雨";
								break;
							case "13":
								wth = "阵雪";
								break;
							case "14":
								wth = "小雪";
								break;
							case "15":
								wth = "中雪";
								break;
							case "16":
								wth = "大雪";
								break;
							case "17":
								wth = "暴雪";
								break;
							case "18":
								wth = "雾";
								break;
							case "19":
								wth = "冻雨";
								break;
							case "20":
								wth = "沙尘暴";
								break;
							case "21":
								wth = "小到中雨";
								break;
							case "22":
								wth = "中到大雨";
								break;
							case "23":
								wth = "大到暴雨";
								break;
							case "24":
								wth = "暴雨到大暴雨";
								break;
							case "25":
								wth = "大雨到特大暴雨";
								break;
							case "26":
								wth = "小到中雪";
								break;
							case "27":
								wth = "中到大雪";
								break;
							case "28":
								wth = "大到暴雪";
								break;
							case "29":
								wth = "浮尘";
								break;
							case "30":
								wth = "扬沙";
								break;
							case "31":
								wth = "强沙尘暴";
								break;
							case "53":
								wth = "霾";
								break;

							}
							mWeather.setText(wth);
							StringBuilder sb = new StringBuilder();
							if (!TextUtils.isEmpty(DataCacheTools.getJsonArray(mContext, Const.WEATHERINFO).getJSONObject(0)
									.getString("fd"))) {
								sb.append(DataCacheTools.getJsonArray(mContext, Const.WEATHERINFO).getJSONObject(0).getString("fd") + "℃");
							}
							if (!TextUtils.isEmpty(DataCacheTools.getJsonArray(mContext, Const.WEATHERINFO).getJSONObject(0)
									.getString("fd"))
									&& !TextUtils.isEmpty(DataCacheTools.getJsonArray(mContext, Const.WEATHERINFO).getJSONObject(0)
											.getString("fc"))) {
								sb.append(" ~ ");
							}
							if (!TextUtils.isEmpty(DataCacheTools.getJsonArray(mContext, Const.WEATHERINFO).getJSONObject(0)
									.getString("fc"))) {
								sb.append(DataCacheTools.getJsonArray(mContext, Const.WEATHERINFO).getJSONObject(0).getString("fc") + "℃");
							}

							mTemp.setText(sb.toString());
							if (!TextUtils.isEmpty(sb.toString())) {
								findViewById(R.id.weather).setVisibility(View.VISIBLE);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}

					}

					@Override
					public void handleFailure(Exception e, String msg) {
						e.printStackTrace();
						findViewById(R.id.weather).setVisibility(View.GONE);
					}
				}, this);
			}
		} catch (JSONException e1) {
			findViewById(R.id.weather).setVisibility(View.GONE);
			e1.printStackTrace();
		}
	}

	/**
	 * 绑定控件
	 * 
	 * 
	 * @author lkx Created at 2015-10-7 上午10:48:29
	 */
	private void ititView() {
		title = (ActivityTitle) findViewById(R.id.infox_techonologyTitle);
		title.setTitle("农技");
		title.setViewVersible(title.rightLayout, title.titleMsg);
		title.setViewGone(title.titleSetting, title.titleRefresh, title.titleOther);
		id_weather_city_tv = (TextView) findViewById(R.id.id_weather_city_tv);
		mWeather = (TextView) findViewById(R.id.id_weather_how_tv);
		mTemp = (TextView) findViewById(R.id.id_weather_number_tv);

		changeBroadcast = new ChangeBroadcast();
		IntentFilter filter = new IntentFilter();
		filter.addAction(Const.CHANGECOUNT);
		this.registerReceiver(changeBroadcast, filter);

		try {
			id_weather_city_tv.setText(SharedPreferencesKit.getJsonObject(this, Const.SP_KEY_BD_LOCAITON).getString("city"));
		} catch (Exception e) {
			Log.e(TAG, e.getMessage(), e);
		}

		// result = (TextView) findViewById(R.id.textView1);

		// mLocationClient = ((Application) getApplication()).mLocationClient;

		// initLocation();

		// getLocationImageView = (ImageView)
		// findViewById(R.id.id_weather_icon);

		// ((Application) getApplication()).mLocationResult = result;
		// getLocationImageView.setOnClickListener(new OnClickListener() {

		// @Override
		// public void onClick(View arg0) {
		// mLocationClient.start();
		// }
		// });

		// parent = (RelativeLayout) findViewById(R.id.id_parent);

		// 农技里边的viewpager初始化..数据适配
		nj_viewpager = (ViewPager) findViewById(R.id.id_nj_viewpager);
		nj_viewpager_list = new ArrayList<Fragment>();  
		nj_fragment_new = new Nj_Fragment_new(this);   
		nj_fragment_near = new Nj_Fragment_near(this);  
		nj_fragment_myquestion = new Nj_Fragment_Myquestion(this);   
		nj_fragment_waitforyou = new Nj_Fragment_Waitforyou(this);  

		nj_viewpager_list.add(nj_fragment_new);
		nj_viewpager_list.add(nj_fragment_near);
		nj_viewpager_list.add(nj_fragment_myquestion);
		nj_viewpager_list.add(nj_fragment_waitforyou);

		radioButton_new = (RadioButton) findViewById(R.id.infox_AgriculturalTechnologyActivity_new);
		radioButton_new.setChecked(true);
		radioButton_near = (RadioButton) findViewById(R.id.infox_AgriculturalTechnologyActivity_nearAnswer);
		radioButton_myquestion = (RadioButton) findViewById(R.id.infox_AgriculturalTechnologyActivity_myQuestion);
		radioButton_waitforyou = (RadioButton) findViewById(R.id.infox_AgriculturalTechnologyActivity_waitAnswer);

		radioButton_near.setOnClickListener(this);
		radioButton_new.setOnClickListener(this);
		radioButton_myquestion.setOnClickListener(this);
		radioButton_waitforyou.setOnClickListener(this);

		nj_viewpager_adapter = new Nj_Pager_Adapter(getSupportFragmentManager(), nj_viewpager_list);
		nj_viewpager.setAdapter(nj_viewpager_adapter);
		nj_viewpager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				switch (arg0) {
				case 0:
					radioButton_new.setChecked(true);

					break;

				case 1:
					radioButton_near.setChecked(true);

					break;
				case 2:
					radioButton_myquestion.setChecked(true);

					break;
				case 3:
					radioButton_waitforyou.setChecked(true);

					break;
				}
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});

		request_ImageView = (ImageView) findViewById(R.id.id_ask_img);

		request_ImageView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (TextUtils.isEmpty(SharedPreferencesKit.getString(AgriculturalTechnologyActivity.this, Const.SP_KEY_USER_ID))) {
					Intent intent = new Intent(AgriculturalTechnologyActivity.this, LoginActivity.class);
					startActivity(intent);
				} else {
					Intent intent = new Intent(AgriculturalTechnologyActivity.this, AskQuestionActivity.class);
					// Intent intent = new
					// Intent(AgriculturalTechnologyActivity.this,
					// SubscriptionColumntwoActivity.class);
					intent.putExtra("userId","");
					startActivity(intent);
				}

			}
		});

		DisplayMetrics dm = getResources().getDisplayMetrics();
		screenWidth = dm.widthPixels;
		screenHeight = dm.heightPixels - 150;

		// request_ImageView.setOnTouchListener(new OnTouchListener() {
		//
		// @Override
		// public boolean onTouch(View arg0, MotionEvent event) {
		//
		// switch (event.getAction()) {
		// case MotionEvent.ACTION_DOWN:
		//
		// lastX = (int) event.getRawX();
		// lastY = (int) event.getRawY();
		// // System.out.println("lastX:"+lastX+",lastY:"+lastY);
		// break;
		// case MotionEvent.ACTION_MOVE:
		// int dx = (int) event.getRawX() - lastX;
		// int dy = (int) event.getRawY() - lastY;
		//
		// int left = request_ImageView.getLeft() + dx;
		// int top = request_ImageView.getTop() + dy;
		// int right = request_ImageView.getRight() + dx;
		// int bottom = request_ImageView.getBottom() + dy;
		//
		// System.out.println("left:" + left);
		// System.out.println("top:" + top);
		// System.out.println("right:" + right);
		// System.out.println("bottom:" + bottom);
		//
		// // 设置不能出界
		// if (left < 0) {
		// left = 0;
		// right = left + request_ImageView.getWidth();
		// }
		//
		// if (right > screenWidth) {
		// right = screenWidth;
		// left = right - request_ImageView.getWidth();
		// }
		//
		// if (top < 0) {
		// top = 0;
		// bottom = top + request_ImageView.getHeight();
		// }
		//
		// if (bottom > screenHeight) {
		// bottom = screenHeight;
		// top = bottom - request_ImageView.getHeight();
		// }
		// request_ImageView.layout(left, top, right, bottom);
		//
		// lastX = (int) event.getRawX();
		// lastY = (int) event.getRawY();
		//
		// break;
		// case MotionEvent.ACTION_UP:
		// break;
		// }
		// return false;
		//
		// }
		// });

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	// private void initLocation() {
	// LocationClientOption option = new LocationClientOption();
	// option.setLocationMode(LocationMode.Hight_Accuracy);//
	// // 可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
	// option.setCoorType("gcj02");// 可选，默认gcj02，设置返回的定位结果坐标系
	// int span = 1000;
	// option.setScanSpan(span);// 可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
	// option.setIsNeedAddress(true);// 可选，设置是否需要地址信息，默认不需要
	// option.setOpenGps(true);// 可选，默认false,设置是否使用gps
	// option.setLocationNotify(true);// 可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
	// option.setIsNeedLocationDescribe(true);//
	// //
	// 可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
	// option.setIsNeedLocationPoiList(true);//
	// // 可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
	// option.setIgnoreKillProcess(false);//
	// // 可选，默认false，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认杀死
	// option.SetIgnoreCacheException(false);// 可选，默认false，设置是否收集CRASH信息，默认收集
	// option.setEnableSimulateGps(false);// 可选，默认false，设置是否需要过滤gps仿真结果，默认需要
	//
	// mLocationClient.setLocOption(option);
	// // mLocationClient.start();
	// }

	// @Override
	// protected void onPause() {
	//
	// mLocationClient.stop();
	// }

	public void exit() {
		if ((System.currentTimeMillis() - exitTime) > 2000) {
			Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
			exitTime = System.currentTimeMillis();
		} else {
			finish();
			Application.getInstance().exit();
			System.exit(0);
		}
	}

	@Override
	public void onBackPressed() {
		exit();

	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.infox_AgriculturalTechnologyActivity_new:
			nj_viewpager.setCurrentItem(0);
			break;
		case R.id.infox_AgriculturalTechnologyActivity_nearAnswer:
			nj_viewpager.setCurrentItem(1);
			break;
		case R.id.infox_AgriculturalTechnologyActivity_myQuestion:
			nj_viewpager.setCurrentItem(2);
			break;
		case R.id.infox_AgriculturalTechnologyActivity_waitAnswer:
			nj_viewpager.setCurrentItem(3);
			break;

		}

	}

	public class ChangeBroadcast extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// 得到数据变化的广播
			if (intent.getAction().equals(Const.CHANGECOUNT)) {
				if(Const.UNREADMESSAGE!=0)
				{
					title.messagenumber.setText(Const.UNREADMESSAGE+"");
					title.messagenumber.setVisibility(View.VISIBLE);
				}else{
					title.messagenumber.setVisibility(View.GONE);
				}

			}

		}

	}

}
